﻿using System.Collections.Generic;
using System.IO;

namespace Red.Core.Network.PacketNetwork
{
    internal class PacketConnection : IRawConnectionInterface
    {
        int _assignedID;
        public int AssignedID
        {
            get { return _assignedID; }
        }

        int _assignedListenerID;
        public int AssignedListenerID
        {
            get { return _assignedListenerID; }
        }

        public ulong TotalBytesReceived
        {
            get;
            private set;
        }

        public int RawConnectionID = -1;
        private IPacketConnectionListener _callback;
        private PacketNetworkParser _parser = new PacketNetworkParser();

        public PacketConnection( int assignedID, IPacketConnectionListener callback )
        {
            _assignedID = assignedID;
            _assignedListenerID = -1;
            _callback = callback;
        }

        public PacketConnection( int assignedID, int assignedListenerID, IPacketConnectionListener callback )
        {
            _assignedID = assignedID;
            _assignedListenerID = assignedListenerID;
            _callback = callback;
        }

        public void OnDisconnected(int connectionID)
        {
            _callback.OnClosed();
        }

        public void OnData(byte[] data, int size, int connectionID)
        {
            TotalBytesReceived += (ulong)size;

            List<MemoryStream> packets = new List<MemoryStream>();
            _parser.AppendAndParse(data, size, ref packets);

            foreach (MemoryStream packet in packets)
            {
                _callback.OnPacket(packet, AssignedID);
            }
        }
    }
}
